package com.hsgene.authority.support;

import com.hsgene.authority.service.OperationAccountPermissionService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

/**
 * 权限初始化Listener，当Spring初始化完成后，初始化部门权限树
 *
 * @author wangbing
 * @version 1.0, 2018/11/9
 */
@Component
public class AuthorityPermissionInitializeListener implements ApplicationListener<ContextRefreshedEvent> {

    private final static Logger LOGGER = LoggerFactory.getLogger(AuthorityPermissionInitializeListener.class);

    /**
     * resource = org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext
     * ApplicationContext = org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext
     *
     * @param event 事件源
     */
    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        if (event.getApplicationContext() instanceof AnnotationConfigServletWebServerApplicationContext) {
            try {
                OperationAccountPermissionService service = event.getApplicationContext().getBean(OperationAccountPermissionService.class);
                if (service != null) {
                    LOGGER.debug("开始初始化部门权限");
                    service.refreshAllDepartmentPermission();
                    LOGGER.debug("部门权限初始化完毕");
                }
            } catch (Exception e) {
                LOGGER.error("部门权限初始化异常");
                e.printStackTrace();
            }
        }
    }
}
